package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.mapper.SysUserMapper;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import com.powernode.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Integer addSysUser(SysUser sysUser) {
        // 新增管理员
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        // 密码必须得加密
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        int i = sysUserMapper.insert(sysUser);
        if (i > 0) {
            Long userId = sysUser.getUserId();
            // 处理管理员与角色的关系
            // 获取用户新增的角色id集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            // 判断是否有值
            if (!CollectionUtils.isEmpty(roleIdList) && roleIdList.size() != 0) {
                List<SysUserRole> sysUserRoles = new ArrayList<>();
                // 循环遍历角色id集合
                roleIdList.forEach(roleId -> {
                    // 创建用户与角色的关系记录
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    // 新增关系，注意：尽量不要在循环中操作数据库，可以进行数据收集然后批量处理
                    sysUserRoles.add(sysUserRole);
                });
                // 批量添加用户与角色的关系
                sysUserRoleService.saveBatch(sysUserRoles);
            }
        }
        return i;
    }

    @Override
    public SysUser querySysUserDetailById(Long id) {
        // 根据标识查询管理员详情
        SysUser sysUser = sysUserMapper.selectById(id);
        // 根据用户标识查询用户与角色的关系记录
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id)
        );
        // 判断是否有值
        if (!CollectionUtils.isEmpty(sysUserRoleList) && sysUserRoleList.size() != 0) {
            // 从用户与角色的关系记录集合中获取角色id集合
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Integer modifySysUser(SysUser sysUser) {
        Long userId = sysUser.getUserId();
        // 删除用户原有的角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId)
        );
        // 新增用户新的角色
        // 获取用户新增的角色id集合
        List<Long> roleIdList = sysUser.getRoleIdList();
        // 判断是否有值
        if (!CollectionUtils.isEmpty(roleIdList) && roleIdList.size() != 0) {
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            // 循环遍历角色id集合
            roleIdList.forEach(roleId -> {
                // 创建用户与角色的关系记录
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                // 新增关系，注意：尽量不要在循环中操作数据库，可以进行数据收集然后批量处理
                sysUserRoles.add(sysUserRole);
            });
            // 批量添加用户与角色的关系
            sysUserRoleService.saveBatch(sysUserRoles);
        }
        // 修改用户信息
        // 获取新密码
        String newPassword = sysUser.getPassword();
        if (StringUtils.hasText(newPassword)) {
            // 有值：用户要修改密码
            sysUser.setPassword(passwordEncoder.encode(newPassword));
        }
        return sysUserMapper.updateById(sysUser);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean removeSysUserByIds(List<Long> userIds) {
        // 删除管理员与角色的关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId,userIds)
        );
        // 删除管理员
        return sysUserMapper.deleteBatchIds(userIds)==userIds.size();
    }
}
